layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
})
layui.use(['form', 'layer', 'utilObj', 'table', 'laypage'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        utilObj = layui.utilObj,
        laypage = layui.laypage,
        table = layui.table;
    var adminUserUrl = "cms/user/findByConditionsPage";
    var deleteUserUrl = "cms/user/deleteAdminUser";
    var enableUserUrl = "cms/user/updateAdminUserState";

    var userPage = {
        getData: function (pageIndex) {
            var requestData = {
                pageIndex: pageIndex - 1,
                pageSize: utilObj.pageSize
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: adminUserUrl,
                type: "POST",
                data: requestData,
                success: function (data) {
                    if (data && data.content) {
                        userPage.tableIns = table.render({
                            elem: '#userList',
                            cellMinWidth: 95,
                            page: false,
                            height: "full-175",
                            limit: utilObj.pageSize,
                            id: "userListTable",
                            cols: [[
                                {
                                    field: 'userName',
                                    title: '用户名',
                                    minWidth: 100,
                                    align: "center"
                                },
                                {
                                    field: 'chineseName',
                                    title: '邮箱',
                                    minWidth: 100,
                                    align: "center"
                                },
                                {
                                    field: 'phone',
                                    title: '手机号',
                                    minWidth: 100,
                                    align: "center"
                                },
                                {
                                    field: 'lastLoginTime',
                                    title: '最后一次登录时间',
                                    minWidth: 100,
                                    align: "center",
                                    templet: function (d) {
                                        return convertDateLongToString(d.lastLoginTime);
                                    }
                                },
                                {
                                    field: 'createTime',
                                    title: '创建时间',
                                    align: 'center',
                                    templet: function (d) {
                                        return convertDateLongToString(d.createTime);
                                    }
                                },
                                {
                                    title: '操作',
                                    minWidth: 150,
                                    templet: '#userListBar',
                                    fixed: "right",
                                    align: "center"
                                }
                            ]],
                            data: data.content
                        });
                        laypage.render({
                            elem: 'userPagination',
                            curr: pageIndex,
                            count: data.totalElements, //数据总数
                            limit: utilObj.pageSize, //每页显示条数
                            jump: function (obj, first) {
                                userPage.current = obj.curr;
                                if (!first) {
                                    userPage.getData(obj.curr);
                                }
                                console.log(obj);
                            }
                        });
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    utilObj.hideLoading();
                }
            });
        },
        enabledUser: function (data, enable) {
            var requestData = {
                userId: data.id,
                state: enable
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: enableUserUrl,
                type: "POST",
                data: requestData,
                success: function (data) {
                    layer.msg(data);
                    utilObj.hideLoading();
                    userPage.getData(userPage.current);
                },
                error: function (err) {
                    layui.msg(err.message);
                    utilObj.hideLoading();
                }
            });
        },
        delUser: function (data) {
            var requestData = {
                userId: data.id
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: deleteUserUrl,
                type: "POST",
                data: requestData,
                success: function (data) {
                    layer.msg(data);
                    utilObj.hideLoading();
                    userPage.getData(userPage.current);
                },
                error: function (err) {
                    layui.msg(err.message);
                    utilObj.hideLoading();
                }
            });
        },
        init: function () {
            userPage.getData(1);
            table.on('tool(userList)', function (obj) {
                    var layEvent = obj.event,
                        data = obj.data;
                    if (layEvent === 'edituser') {
                        addUser(data);
                    } else if (layEvent === 'del') {
                        var usableText = "是否确定删除此用户？"
                        layer.confirm(usableText, {
                            icon: 3,
                            title: '系统提示',
                            cancel: function (index) {
                                layer.close(index);
                            }
                        }, function (index) {
                            layer.close(index);
                            userPage.delUser(data);
                        }, function (index) {
                            layer.close(index);
                        });
                    } else if (layEvent === 'disabled') {
                        var usableText = "是否确定禁用此用户？"
                        layer.confirm(usableText, {
                            icon: 3,
                            title: '系统提示',
                            cancel: function (index) {
                                layer.close(index);
                            }
                        }, function (index) {
                            layer.close(index);
                            userPage.enabledUser(data, 0);
                        }, function (index) {
                            layer.close(index);
                        });

                    } else if (layEvent === 'enabled') {
                        var usableText = "是否确定启用此用户？"
                        layer.confirm(usableText, {
                            icon: 3,
                            title: '系统提示',
                            cancel: function (index) {
                                layer.close(index);
                            }
                        }, function (index) {
                            layer.close(index);
                            userPage.enabledUser(data, 1);
                        }, function (index) {
                            layer.close(index);
                        });
                    } else if (layEvent === 'editadmin') {
                        addUser(data);
                    }
                }
            );
        }
    }
    userPage.init();

    //添加用户
    function addUser(edit) {
        var title = "添加用户";
        if (edit) {
            title = "编辑用户";
        }
        var index = layui.layer.open({
            title: title,
            type: 2,
            content: "adminUserAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".user-id").val(edit.id);  //用户id
                    body.find(".userName").val(edit.userName).addClass("layui-disabled").attr('disabled','disabled');  //登录名
                    body.find(".email").val(edit.chineseName);  //邮箱
                    body.find(".userPhone").val(edit.phone);  //手机号
                    // body.find(".userPwd").val("");
                    // body.find(".userConfirmPwd").val("");
                    //设置角色不管用
                    body.find(".userRole input[value=" + edit.role + "]").prop("checked", "checked");  //用户角色
                    body.find(".userState input[value=" + edit.isvalid + "]").prop("checked", "checked");  //状态
                    var iframeWindow = layero.find('iframe')[0].contentWindow;
                    iframeWindow.layui.form.render();
                }
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }

    $(".addNews_btn").click(function () {
        addUser();
    })

    function convertDateLongToString(str) {
        if (str == "" || str == null || str == undefined) {
            return "";
        } else {
            return new Date(str).format('yyyy-MM-dd hh:mm:ss');
        }
    }

    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

})
